package com.seres.gate.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description : zuul整合所有服务接口文档
 * @ClassName : SwaggerDocumentationConfig
 * @Author : 程磊
 * @Date: 2020-06-29 12:52
 */
@Component
@Primary
@RefreshScope
public class RegistrySwaggerResourcesProvider implements SwaggerResourcesProvider {

    @Value("${debug:false}")
    private boolean debug;

    @Value("${spring.application.name}")
    private String applicationName;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Override
    public List<SwaggerResource> get() {
        //如果正式服，不能出现swagger相关的任何接口
        if (!debug) {
            return new ArrayList<>();
        }
        List<SwaggerResource> resources = new ArrayList<>();
        // 排除自身，将其他的服务添加进去
        discoveryClient
                .getServices()
                .stream()
                .filter(s -> !StringUtils.equals(s, applicationName))
                .forEach(name -> {
                    resources.add(swaggerResource(name, "/" + name + "/v2/api-docs", "2.0"));
                });
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }
}
